<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as monaco from 'monaco-editor'
import { useMockStore } from '../store/mockStore'
 
const mockStore = useMockStore()

const editorContainer = ref<HTMLDivElement | null>(null)
let editor: monaco.editor.IStandaloneCodeEditor | null = null

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'json'
  },
  readOnly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

// 监听modelValue的变化，更新编辑器的值
watch(() => props.modelValue, (newValue) => {
  if (editor && newValue !== editor.getValue()) {
    editor.setValue(newValue)
  }
})

onMounted(() => {
  if (editorContainer.value) {
    editor = monaco.editor.create(editorContainer.value, {
      value: props.modelValue,
      language: props.language,
      theme: 'vs-dark',
      automaticLayout: true,
      wordWrap: 'on',
      wrappingIndent: 'indent',
      smoothScrolling: false,
      minimap: { enabled: false },
      readOnly: props.readOnly
    })

    editor.onDidChangeModelContent(() => {
      const value = editor?.getValue()
      if (value) {
        emit('update:modelValue', value)
      }
    })
  }
})
</script>

<template>
  <div class="code-editor">
    <div ref="editorContainer" class="editor-container"></div>
  </div>
</template>

<style scoped>
.code-editor {
  width: 100%;
  height: 400px;
  border: 1px solid #ddd;
}

.editor-container {
  width: 100%;
  height: 100%;
}
</style>